import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Modal from 'react-modal';
import ReactDOM from 'react-dom';

import { hidePathInputBar, updatePathInputBar, selectDirectory } from '../../actions/path-input-bar-actions.js';

/**
 * 路径输入框
 * @class {PathInputBar}
 * @extends {React.Component}
 */
@connect(state => ({
    pathInputBar: state.pathInputBar
}))
export default class PathInputBar extends Component {

    /**
     * 处理键盘事件
     * @param  {Event} event
     */
    handleKeyUp = (event) => {
        if (event.key === 'Enter') {
            this.props.dispatch(hidePathInputBar(true));
        }

        if (event.key === 'Escape') {
            this.props.dispatch(hidePathInputBar());
        }

        if (event.key === 'Tab') {
            this.props.dispatch(selectDirectory(event.target.value))
        }
    };

    /**
     * 加载后自动高亮
     */
    handleAfterOpen = () => {
        ReactDOM.findDOMNode(this.refs.pathInputBox).focus();
    };

    render() {
        const { pathInputBar, dispatch } = this.props;

        return (
            <Modal isOpen={pathInputBar.isOpen}
                onAfterOpen={this.handleAfterOpen}
                className="modal path-input-bar"
                contentLabel="Example Modal"
                overlayClassName="modal-overlay bottom">
                <div className="path-input-bar">
                    <label htmlFor="path-input-box" className="path-input-box">
                        <span>{pathInputBar.label}</span>
                        <input ref="pathInputBox"
                            type="text"
                            value={pathInputBar.value}
                            onKeyUp={this.handleKeyUp}
                            onChange={event => dispatch(updatePathInputBar(event.target.value))} />
                    </label>
                </div>
            </Modal>
        );
    }
}